package com.zcsy.manage.web.complain;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zcsy.commons.constants.Constants;
import com.zcsy.commons.model.RequestConstants;
import com.zcsy.commons.model.RequestJson;
import com.zcsy.commons.util.DateUtils;
import com.zcsy.manage.model.complain.ComplaintsInfo;
import com.zcsy.manage.model.complain.ComplaintsReply;
import com.zcsy.manage.model.system.Dict;
import com.zcsy.manage.model.system.User;
import com.zcsy.manage.service.complain.IComplaintsInfoService;
import com.zcsy.manage.service.complain.IComplaintsReplyService;
import com.zcsy.manage.service.system.IDictService;
import com.zcsy.manage.web.common.LogUtils;
import com.zcsy.manage.web.tools.JExcelReport;

/**
 * @Title: ComplaintsInfoController.java
 * @Package： com.zcsy.manage.web.property
 * @Description: 投诉信息控制层管理类
 * @author xujl
 * @Copyright: 2015 武汉中财数元信息技术有限公司 All rights reserved.
 * @date 2016年4月14日
 * @version 1.0
 * @see JDK1.7.0_75
 * @since
 */
@Controller
@RequestMapping(value = "/complainInfo")
public class ComplaintsInfoController {

    @Autowired
    private IComplaintsInfoService infoService;

    @Autowired
    private IComplaintsReplyService replyService;

    @Autowired
    private IDictService dictService;
    
    private final static int PINGTAI = 0;//投诉平台或商家
    /**
     * @Description 分页获取投诉数据列表
     * @param model
     * @param pNo
     *            页数
     * @param title
     *            标题
     * @param state
     *            状态
     * @param type
     *            类型
     * @param complainType
     *            投诉对象:0投诉平台或商家，1投诉物业
     * @param level
     *            危害等级
     * @param beginDate
     *            开始时间
     * @param endDate
     *            结束时间
     * @param req
     *            用户的请求
     * @return 返回查询的结果
     * @author xujl
     * @date 2016年4月18日
     * @see
     */
    @RequestMapping(value = "infoList", method = RequestMethod.GET)
    public String infoList(Model model, Integer pNo, Integer pSize, String title, Integer state, Integer type,Integer complainType,
            Integer level, String beginDate, String endDate, HttpServletRequest req) {
        if (pNo == null) {
            pNo = Constants.PAGE_NO;
        }

		Integer pageSize;
		if (pSize == null) {
			pageSize = Constants.PAGE_SIZE;
		} else {
			switch (pSize) {
				case 0: pageSize = Constants.PAGE_SIZE;
				break;
				case 1: pageSize = Constants.PAGE_SIZE_TWENTY;
				break;
				case 2: pageSize = Constants.PAGE_SIZE_FIFTY;
				break;
				default:pageSize = Constants.PAGE_SIZE;
				break;
			}
		}
		
        String url="";

        // 此处添加PageHelper将会走拦截器，进行分页，分页方法只针对紧跟着PageHelper的查询方法有效
        PageHelper.startPage(pNo, pageSize);

        ComplaintsInfo info = new ComplaintsInfo();

        // 标题不为空时，设置标题
        if (StringUtils.isNotEmpty(title)) {
            info.setTitle(title);
        }
        if (StringUtils.isNotEmpty(beginDate)) {
            info.setBeginTime(beginDate);
        }
        if (StringUtils.isNotEmpty(endDate)) {
            info.setEndTime(endDate);
        }

        if (type == null) {
            type = Constants.SELECT_NONE;
        }
        if (state == null) {
            state = Constants.SELECT_NONE;
        }
        if (level == null) {
            level = Constants.SELECT_NONE;
        }
        if (complainType == null) {
            complainType = Constants.SELECT_NONE;
        }

        info.setType(type);
        info.setState(state);
        info.setLevel(level);
        info.setComplainType(complainType);

        List<ComplaintsInfo> rInfoList = infoService.selectByKeyword(info);
        PageInfo<ComplaintsInfo> pageInfo = new PageInfo<ComplaintsInfo>(rInfoList);

        model.addAttribute("complaintsInfo", pageInfo);
        model.addAttribute("currentPage", pNo);
        model.addAttribute("title", title);
		model.addAttribute("pSize", pSize);
        model.addAttribute("state", state);
        model.addAttribute("level", level);
        model.addAttribute("type", type);
        model.addAttribute("complainType", complainType);
        model.addAttribute("beginDate", beginDate);
        model.addAttribute("endDate", endDate);
        
        List<Dict> typeList = dictService.getDictFromCache("complainType");
        model.addAttribute("typeList", typeList);
        
        List<Dict> complainState = dictService.getDictFromCache("complainState");
        model.addAttribute("complainState", complainState);

        List<Dict> harmLevel = dictService.getDictFromCache("harmLevel");
        model.addAttribute("harmLevel", harmLevel);

		List<Dict> pageSizes = dictService.getDictFromCache("pageSize");
		model.addAttribute("pageSizes", pageSizes);

        if (complainType == PINGTAI) {
            url="complain/complaintsInfoList";
        } else url="complain/complaintsWuYeList";

        return url;
    }

    /**
     * @Description 编辑投诉<br>
     * @param id 主键id
     * @return 跳转画面URL
     * @author xujl
     * @date 2016年4月14日
     * @see
     */
    @RequestMapping(value = "editComplaintsInfo", method = RequestMethod.GET)
    public String editrepairInfo(Model model, String id, Integer type,Integer complainType) {

        String url = "complain/complaintsInfoEdit";

        try {
            model.addAttribute("type", type);

            // 从缓存不为空则从缓存中获取通知类型，为空则从数据字典获取
            List<Dict> titleList = dictService.getDictFromCache("normalTitle");
            model.addAttribute("titleList", titleList);

            if (type == Constants.ADD_MEMO) {
                ComplaintsInfo complaintsInfo = infoService.selectByPrimaryKey(id);
                model.addAttribute("repairInfo", complaintsInfo);
            }
            if (type == Constants.SEE_REVIEW) {
                ComplaintsInfo complaintsInfo = infoService.selectByPrimaryKey(id);
                List<ComplaintsReply> replyList = replyService.selectByInfoId(id);

                model.addAttribute("complaintsInfo", complaintsInfo);
                model.addAttribute("replyList", replyList);
                url = "complain/complaintsInfoDetail";
            }

            model.addAttribute("complainType", complainType);
        } catch (Exception e) {
        }
        return url;
    }

    /**
     * @Description 根据多个id删除投诉信息<br>
     * @param iDs
     *            多个id
     * @param req
     *            用户请求
     * @return 请求结果
     * @author xujl
     * @date 2016年4月14日
     * @see
     */
    @RequestMapping(value = "deleteInfo", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson deleteInfo(String iDs, HttpServletRequest request) {

        RequestJson result = new RequestJson();
        User user = (User)request.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        try {
            String ids[] = iDs.split("\\,");
            for (int i = 0; i < ids.length; i++ ) {
                infoService.deleteByPrimaryKey(ids[i]);
            }
            result.setSuccess(true);
            LogUtils.insertLog("用户删除投诉建议", user.getId(), request);
        } catch (NumberFormatException e) {
            result.setSuccess(false);
            result.setMsg("操作失败");
        }
        return result;
    }
    
    /**
     * @Description 导出物业费清单<br>
     * 
     * @param response 
     * @author xujl
     * @date 2016年5月3日
     * @see 
     */
    @RequestMapping("/exportExcel")
    @ResponseBody
    public void exportExcel(String title, Integer state, Integer type,Integer complainType,
            Integer level, String beginDate, String endDate,HttpServletResponse response, HttpServletRequest request) {
        List<ComplaintsInfo> list;
        ComplaintsInfo info = new ComplaintsInfo();
        User user = (User)request.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        
        if (StringUtils.isNotEmpty(title)) {
            info.setTitle(title);
        }
        if (StringUtils.isNotEmpty(beginDate)) {
            info.setBeginTime(beginDate);
        }
        if (StringUtils.isNotEmpty(endDate)) {
            info.setEndTime(endDate);
        }

        if (type == null) {
            type = Constants.SELECT_NONE;
        }
        if (state == null) {
            state = Constants.SELECT_NONE;
        }
        if (level == null) {
            level = Constants.SELECT_NONE;
        }

        info.setType(type);
        info.setState(state);
        info.setLevel(level);
        info.setComplainType(complainType);
        
        try {
            //得到导出的数据列表
            list = infoService.selectByKeyword(info);
            
            // 将订单对象转化为到处所需要的数据格式
	        Integer cType, cState, cLevel;
	        String  tLabel, sLabel, lLabel;
            if (list.size() > 0) {
                ArrayList<ArrayList<String>> dataList = new ArrayList<ArrayList<String>>();
                int index =1;
                for(ComplaintsInfo infos : list){
                    ArrayList<String> temp = new ArrayList<String>();
                    //序号
                    temp.add(String.valueOf(index++));
                    temp.add(infos.getTitle());
                    temp.add(infos.getHouseName());
                    temp.add(infos.getContactor());
                    cType = infos.getType();
                    tLabel = dictService.selectByFilter(cType,"complainType").getLabel();
                    temp.add(tLabel);
                    
                    cLevel = infos.getLevel();
                    lLabel = dictService.selectByFilter(cLevel,"harmLevel").getLabel();
                    temp.add(lLabel);
                    
                    cState = infos.getState();
                    sLabel = dictService.selectByFilter(cState,"complainState").getLabel();
                    temp.add(sLabel);
                    
                    dataList.add(temp);
                }
                // 导出标题列
                String[] rows = new String[] {"序号","标题","房屋名","联系人","投诉类型","危害程度","状态"};
                // 导出excel文件每列宽度
                int[] style = new int[] {5,20,20,20,20,20,20};
                String sheetName ="";
                String fileName ="";
                // Excel文件sheet名称
                if (complainType == PINGTAI) {
                    sheetName = "平台投诉清单"+DateUtils.getCurrentDate();
                    fileName = "平台投诉清单"; 
                } else {
                    sheetName = "物业投诉清单"+DateUtils.getCurrentDate();
                    fileName = "物业投诉清单"; 
                }
                
                doExecl(response,fileName,sheetName, dataList, rows, style);
                LogUtils.insertLog("用户导出投诉建议清单", user.getId(), request);
            }
        } catch(Exception e) {
            return;
        }
    }
    
    
    
    /**
     * @Description 通过传入的对象信息集合产生的excel表格<br>
     * @param response 用户响应
     * @param sheetName excel表名称
     * @param dataList 传入的数据列表
     * @param rows excel表的列控制，名称
     * @param style 规定列宽等样式
     * @throws Exception 
     * @author xujl
     * @date 2016年5月3日
     * @see 
     */
    private void doExecl(HttpServletResponse response,String tempName, String sheetName,
            ArrayList<ArrayList<String>> dataList, String[] rows, int[] style) throws Exception {
        //输出的excel名称为中文，否则发生错误
        String tempFileName = tempName+".xls";
        String fileName = new String(tempFileName.getBytes("GB2312"), "ISO_8859_1"); 
        
        ServletOutputStream fout = response.getOutputStream();
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "filename="+fileName+"");
        JExcelReport jexcelOutStream = new JExcelReport();
        try {
            jexcelOutStream.excelreport(sheetName, dataList, rows, fout, style);
            fout.flush();
            fout.close();
        } catch (Exception e){
        }
        
    }
    
}
